package syncer

import (
	"encoding/json"
	"gluenet/pkg/apis"
	"gluenet/pkg/meta"
	"gluenet/pkg/ops"
	"time"
)

func syncDagLinkerd(c *apis.StorageContext) {
	var intances []meta.Instance
	if err := c.DataBase.InstanceListAll(&intances); err != nil {
		c.Logger.Errorf("query instance %v", err)
		return
	}

	var dag = make(map[string]interface{})
	for _, v := range intances {
		var irun *meta.InstanceRunTime
		if err := c.DataBase.InstanceRuntimeGet(v.Guid, &irun); err != nil {
			c.Logger.Errorf("query instance runtime %v", err)
			continue
		}

		// todo get nodes
		var nodes = make(map[string]interface{})
		if err := json.Unmarshal([]byte(irun.ContainersInfo), &nodes); err != nil {
			c.Logger.Warnf("unmarshall k8s container info  %v", err)
			continue
		}

		// todo get links
		var data *meta.Metrics
		if err := c.DataBase.MetricsServiceMeshQuery(ops.TCPOpenTotal, v.Guid, v.Platform, &data); err != nil {
			c.Logger.Debugf("instance %v get service mesh %v", v.Name, err)
			continue
		}

		edges := data.Metrics.([]map[string]interface{})
		links := make([]interface{}, len(edges))
		for i, vn := range edges {
			links[i] = map[string]interface{}{
				"source": vn["container"],
				"target": vn["dst_container"],
				"value":  vn["value"],
			}
		}

		// deal data
		dag[v.Guid] = map[string]interface{}{
			"dag_nodes": nodes,
			"dag_links": links,
		}
	}

	bts, _ := json.Marshal(dag)
	//orm2.SaveResourceDag(c, "glue", time.Now().Unix(), string(bts))
	c.DataBase.DagPut(ops.DagLinkerd, &meta.Dag{
		UpdateTime:  time.Now().String(),
		InstanceDag: string(bts),
	})
}
